# -*- coding: utf-8 -*-
# @Author  : Pony
# @Time    : 2021/10/26 下午2:36
# Description: redis资源管理器， redis发布订阅

import redis
from contextlib import contextmanager


@contextmanager
def redis_connect():
    redis_conn = redis.Redis(host='localhost', port=16379, password='123456')
    yield redis_conn
    redis_conn.close()


class RedisHelper(object):

    def __init__(self, channel_name):
        # self.__conn = redis.Redis(host='localhost', port=16379, password='123456')
        # self.__conn = redis.Redis(host='172.20.8.233', port=16379, password='123456')
        self.__conn = redis.Redis(host='172.20.8.56', port=16379, password='1234356')
        self.channel_name = channel_name

    def public(self, msg):
        """
        在指定频道上发布消息
        :param msg:
        :return:
        """
        # publish(): 在指定频道上发布消息，返回订阅者的数量
        self.__conn.publish(self.channel_name, msg)
        return True

    def subscribe(self):
        # 返回发布订阅对象，通过这个对象你能1）订阅频道 2）监听频道中的消息
        pub = self.__conn.pubsub()
        # 订阅某个频道，与publish()中指定的频道一样。消息会发布到这个频道中
        pub.subscribe(self.channel_name)
        return pub
